package com.ruoyi.core.service.impl;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.AliyunSmsUtils;
import com.ruoyi.common.utils.KdniaoApiUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.core.domain.*;
import com.ruoyi.core.domain.vo.GiftCardVo;
import com.ruoyi.core.mapper.GiftCardMapper;
import com.ruoyi.core.service.IProductService;
import com.ruoyi.core.service.ISmsRecordService;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.core.mapper.OrdersMapper;
import com.ruoyi.core.service.IOrdersService;
import com.ruoyi.common.core.text.Convert;

/**
 * 快递发货Service业务层处理
 * 
 * @author lgc
 * @date 2020-08-10
 */
@Service
public class OrdersServiceImpl implements IOrdersService 
{
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private GiftCardMapper giftCardMapper;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WeixinService weixinService;

    @Autowired
    private ISmsRecordService smsRecordService;
    @Value("${wechat.templateId}")
    private String templateId;


    @Autowired
    private IProductService productService;

    /**
     * 查询快递发货
     * 
     * @param ordersId 快递发货ID
     * @return 快递发货
     */
    @Override
    public Orders selectOrdersById(String ordersId)
    {
        return ordersMapper.selectOrdersById(ordersId);
    }

    /**
     * 查询快递发货列表
     * 
     * @param orders 快递发货
     * @return 快递发货
     */
    @Override
    public List<Orders> selectOrdersList(Orders orders)
    {
        return ordersMapper.selectOrdersList(orders);
    }

    /**
     * 新增快递发货
     * 
     * @param orders 快递发货
     * @return 结果
     */
    @Override
    public Orders insertOrders(Orders orders)
    {
        Long giftCardId = orders.getGiftCardId();

        GiftCard giftCard = new GiftCard();
        giftCard.setGiftCardId(giftCardId);
        List<GiftCardVo> giftCardVos = giftCardMapper.selectGiftCardList(giftCard);

        if (giftCardVos.isEmpty())
            throw new BusinessException("礼品卡不存在");

        GiftCardVo giftCardVo = giftCardVos.get(0);
        if (1 == giftCardVo.getIsUsed()) {
            throw new BusinessException("该提货码已被使用");
        }

        //添加信息
        Date date = new Date();
        orders.setCreatedDate(date);
        orders.setState(0);
        if (orders.getShopId()!=null){
            orders.setOrderType(1);
        }else {
            orders.setOrderType(2);
        }
        orders.setFwCode(giftCardVo.getFwCode());
        orders.setLogisticsCode(giftCardVo.getCode());
        orders.setCodeIndex(giftCardVo.getIndex().toString());
        ordersMapper.insertOrders(orders);

        //更新卡劵使用情况
        giftCard.setIsUsed(1);
        giftCardMapper.updateGiftCard(giftCard);

        return orders;
    }

    /**
     * 修改快递发货
     * 
     * @param orders 快递发货
     * @return 结果
     */
    @Override
    public int updateOrders(Orders orders){
        Date now = Calendar.getInstance().getTime();
        orders.setLastUpdatedDate(now);
        return ordersMapper.updateOrders(orders);
    }

    private void insertSmsRecord(Orders orders) {
        SmsRecord smsRecord = new SmsRecord();
        smsRecord.setCreatedDate(new Date());
        smsRecord.setOrdersId(orders.getOrdersId());
        smsRecord.setUserId(orders.getLastUpdatedBy());
        smsRecordService.insertSmsRecord(smsRecord);
    }

    private void sendSms(Orders orders) {
        GiftCard giftCard = giftCardMapper.selectGiftCardById(orders.getGiftCardId());
        Integer productId = giftCard.getProductId();
        Product product = productService.selectProductById(productId.longValue());

        SendSmsResponse response = null;
        try {
            response = AliyunSmsUtils.sendSms(orders.getTel(), product.getProductName(), orders.getLogisticsName(), orders.getExpressNumber());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        if (response==null){
            throw new BusinessException("短信发送异常");
        }
    }

    /**
     * 删除快递发货对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteOrdersByIds(String ids)
    {
        return ordersMapper.deleteOrdersByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除快递发货信息
     * 
     * @param ordersId 快递发货ID
     * @return 结果
     */
    @Override
    public int deleteOrdersById(String ordersId)
    {
        return ordersMapper.deleteOrdersById(ordersId);
    }

    @Override
    public List<ExpressOrders> selectExpressOrdersList(Orders orders) {
        return ordersMapper.selectExpressOrdersList(orders);
    }

    @Override
    public int updateByOrdersId(Long ordersId, Long userId) {
        Date date = new Date();

        Orders orders = new Orders();
        orders.setOrdersId(ordersId);
        orders.setLastUpdatedDate(date);
        orders.setLastUpdatedBy(userId);
        orders.setFinishDate(date);
        orders.setState(1);

        return ordersMapper.updateOrders(orders);
    }
    @Override
    public int updateByOrdersId(Orders orders) {
        Date date = new Date();
        orders.setLastUpdatedDate(date);
        orders.setFinishDate(date);
        orders.setState(1);
        return ordersMapper.updateOrders(orders);
    }


    @Override
    public String getLogisticsMsgByNumber(String expressNumber) {
//        System.out.println("expressNumber = " + expressNumber);
        String result = null;
        Orders orders = ordersMapper.selectOrdersByNumber(expressNumber);
        if (orders!=null){
            //物流单号已发货超过10天不支持再查询
            Instant instant = orders.getFinishDate().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            LocalDateTime now = LocalDateTime.now();
            //不是同一月份
            if (!now.getMonth().equals(localDateTime.getMonth())){
                long l = Duration.between(now, localDateTime).toDays();
                //且超过10天
                if (Math.abs(l)>10) {
                    return "已逾期查询";
                }
            }
            try {
                result = KdniaoApiUtils.getOrderTracesByJson(expressNumber);
                if (StringUtils.isNotEmpty(result)){
                    Map<String, String> shippers = (Map<String, String>) JSONObject.parseObject(result)
                            .getJSONArray("Shippers")
                            .get(0);

                    String ShipperCode = shippers.get("ShipperCode");
                    result = KdniaoApiUtils.getOrderTracesByJson(ShipperCode,orders.getTel(),expressNumber);
                    System.out.println("result = " + result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 根据物流码查物流公司
     * @param expNo
     * @return
     */
    @Override
    public AjaxResult KdApiOrderDistinguish(String expNo) {
        String result = null;
        if (StringUtils.isEmpty(expNo)){
          return   AjaxResult.error("该码为空");
        }
        try {
            result = KdniaoApiUtils.getOrderTracesByJson(expNo);
            if (StringUtils.isNotEmpty(result)){
                JSONArray shipperArray = JSONObject.parseObject(result)
                        .getJSONArray("Shippers");
                if (shipperArray==null){
                    return  AjaxResult.error("尚未识别该快递单号！请选择相应的快递公司。");
                }else {
                    Map<String, String> shippers = (Map<String, String>) shipperArray.get(0);
                    result = shippers.get("ShipperName");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  AjaxResult.success(result);
    }

    @Override
    public void deliveryByIdAndNumber(Orders orders, Long smsBalance) {
            //发送公众号模版消息
            weixinService.sendMsg(wxMpService,templateId,orders,orders.getOpenId());

            //判断该用户是否还剩余Sms
            if (smsBalance>0){
                //发送短信SMS信息提醒
                sendSms(orders);
                // 添加短信发送记录
                insertSmsRecord(orders);
            }


    }
}
